package cn.itcast.itcaststore.serive.impl;

import cn.itcast.itcaststore.dao.UserDao;
import cn.itcast.itcaststore.dao.impl.UserDaoImpl;
import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.exception.ActiveUserException;
import cn.itcast.itcaststore.exception.LoginException;
import cn.itcast.itcaststore.exception.RegisterException;
import cn.itcast.itcaststore.serive.UserService;
import cn.itcast.itcaststore.utils.MailUtils;

import java.sql.SQLException;
import java.util.Date;

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    @Override
    public void register(User user) throws RegisterException {
        try {
            userDao.addUser(user);
            //发送激活邮件
            String emailMag="感谢您注册网上书城，单击"+"<a href='http://localhost:8080/web_test_war_exploded/activeUser?activeCode="
                    +user.getActiveCode()+"'>&nbsp;激活&nbsp;</a>后使用。"
                    +"<br/>为保障您的账户安全，请在24小时内完成激活操作";
            MailUtils.sendMail(user.getEmail(),emailMag,"测试邮件");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RegisterException("注册失败");
        }
    }

    @Override
    public User login(String username, String password) throws LoginException {
        try {
            //根据登录时表单输入的用户名和密码，查找用户
            User user=userDao.findUserByUsernameAndPassword(username,password);
            //如果找到，还需要确定用户是否为激活用户
            if (user!=null){
                //只有是激活用户才能登录，否则提示“用户未激活”
                if (user.getState()==1){
                    return user;
                }
                throw new LoginException("用户未激活");
            }
            throw new LoginException("用户名或密码错误");
        } catch (SQLException | LoginException e) {
            e.printStackTrace();
            throw new LoginException("登陆失败");
        }
    }

    @Override
    public int activeUser(String activeCode) throws ActiveUserException {
        try {
            // 根据激活码查找用户
            User user = userDao.findUserByActiveCode(activeCode);
            if (user == null) {
                throw new ActiveUserException("激活用户失败");
            }
            // 判断激活码是否过期 24小时内激活有效.
            // 1.得到注册时间
            Date registTime = user.getRegistTime();
            // 2.判断是否超时
            long time = System.currentTimeMillis() - registTime.getTime();
            if (time / 1000 / 60 / 60 > 24) {
                throw new ActiveUserException("激活码过期");
            }
            // 激活用户，就是修改用户的state状态
            int i = userDao.activeUser(activeCode);
            return i;
        } catch (SQLException | ActiveUserException e) {
            e.printStackTrace();
            throw new ActiveUserException("激活用户失败");
        }
    }
}
